<script setup lang="ts">
/**
 * 账号验证流程：
 * 
 * 1.获取到输入的邮箱及验证码
 * 
 * 2.调用获取邮箱验证码接口
 * 
 * 3.获取邮箱验证码之后，获取按钮需要暂时禁用(60s)
 * 
 * 4.获取到验证码之后，下一步的时候校验验证码是否合法，如果合法则进入下一步
 * 
 */
import {
  defineEmits,
  onUnmounted,
  reactive,
  ref,
} from 'vue';

import  {
  AxiosError,
  AxiosResponse,
} from 'axios';
import  {
  FormInstance,
  FormRules,
} from 'element-plus';
import {
  ElLoading,
  ElMessage,
} from 'element-plus';
import { useRouter } from 'vue-router';

import api from '@/utils/api';

// 路由控制
const router = useRouter();

//自定义事件
const emit = defineEmits(['next']);
// 表单数据
const account = reactive({
    account: '',
    captcha: '',
    verifycode: ''
});
//表单的实例
const formRef = ref();
//数据校验
const rules = reactive<FormRules<typeof account>>({
    account: [{ required: true, message: '请输入电子邮箱', trigger: 'blur' }],
    captcha: [{ required: true, message: '请输入图像验证码', trigger: 'blur' }],
    verifycode: [{ required: true, message: '请输入邮箱验证码', trigger: 'blur' }],
})
//验证码
const captchaSrc = ref('/api/register/captcha');
//验证码的刷新
const refreshCaptcha = () => {
    captchaSrc.value = '/api/register/captcha?t_=' + new Date().getTime()
}
//定义定时器
let timer: number | undefined;

//验证码倒计时
let verifycodeTime = ref(0);
//获取邮箱验证码
const getSmscode = () => {
    if (!account.account || !account.captcha) {
        ElMessage.error('请输入电子邮箱及验证码');
        return;
    }
    //显示加载动画
    const loading = ElLoading.service({
        lock: true,
        text: '正在处理',
        background: 'rgba(0, 0, 0, 0.7)',
    });
    api.post('/api/register/getSmscode', {
        phone: account.account,
        captcha: account.captcha
    }).then((response: AxiosResponse<any>) => {
        if (response.status != 200 || !response.data || response.data.code != 200) {
            if (response.data) {
                ElMessage.error('获取失败:' + response.data.msg)
            } else {
                ElMessage.error('获取失败!')
            }
            return;
        }
        //提示邮箱验证码已发送
        ElMessage({
            message: '邮箱验证码已发送，3分钟之内有效！',
            type: 'success',
        })
        //限制获取验证码按钮一分钟之内不能重复点击
        verifycodeTime.value = 60;
        timer = setInterval(() => {
            verifycodeTime.value--;
            if (verifycodeTime.value <= 0) {
                verifycodeTime.value = 0;
                clearInterval(timer);
                timer = null;
            }
        }, 1000);
    }).catch((error: AxiosError<any>) => {
        if (error.response && error.response.data) {
            ElMessage.error(error.response.data.msg)
            return;
        }
        ElMessage.error('操作异常：' + error.message)
    }).finally(() => {
        loading.close();
    });
}
//提交表单
const submitForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    formEl.validate((isValid: boolean) => {
        if (!isValid) {
            return;
        }
        //显示加载动画
        const loading = ElLoading.service({
            lock: true,
            text: '正在处理',
            background: 'rgba(0, 0, 0, 0.7)',
        });
        //请求接口，进行登陆
        api.post('/api/register/validateSmscode', {
            verifycode: account.verifycode
        }).then((response: AxiosResponse<any>) => {
            if (response.status != 200 || !response.data || response.data.code != 200) {
                if (response.data) {
                    ElMessage.error('处理失败:' + response.data.msg)
                } else {
                    ElMessage.error('处理失败!')
                }
                return;
            }
            emit('next', {
                account: account.account,
                verifycode: account.verifycode,
                captcha: account.captcha
            });
        }).catch((error: AxiosError<any>) => {
            if (error.response && error.response.data) {
                ElMessage.error(error.response.data.msg)
                return;
            }
            ElMessage.error('操作异常：' + error.message)
        }).finally(() => {
            loading.close();
        });
    })
}
//取消
const cancel = () => {
    router.push('/login');
}
onUnmounted(() => {
    //清除定时器
    timer && clearInterval(timer);
})

</script>

<template>
    <!-- 电子邮箱校验 -->
    <el-form ref="formRef" :model="account" :rules="rules" size="large" label-width="120" class="accountForm"
        status-icon>
        <el-form-item label="电子邮箱：" prop="account">
            <el-input v-model="account.account" placeholder="请输入您的电子邮箱" suffix-icon="Message" />
        </el-form-item>
        <el-form-item label="图像验证码：" prop="captcha">
            <div class="flex">
                <div class="flexItem">
                    <el-input v-model="account.captcha" placeholder="请输入图形验证码" />
                </div>
                <div class="captchaPanel">
                    <img :src="captchaSrc" @click="refreshCaptcha">
                </div>
            </div>
        </el-form-item>
        <el-form-item label="邮箱验证码：" prop="verifycode">
            <div class="flex">
                <div class="flexItem">
                    <el-input v-model="account.verifycode" placeholder="请输入邮箱验证码" suffix-icon="Message" />
                </div>
                <div class="verifycodePanel">
                    <el-button @click="getSmscode" :disabled="verifycodeTime > 0">{{ verifycodeTime > 0 ? verifycodeTime
        +
        '秒之后再试' : '获取验证码' }}</el-button>
                </div>
            </div>
        </el-form-item>
        <el-form-item label="">
            <div class="formBtns">
                <el-button type="danger" @click="cancel">取消</el-button>
                <el-button type="primary" @click="submitForm(formRef)">
                    下一步
                </el-button>
            </div>
        </el-form-item>
    </el-form>
</template>

<style scoped>
.accountForm {
    width: 50%;
    margin: 0 auto;
}

.accountForm .formBtns {
    margin: 0 auto;
}

.accountForm .formBtns .el-button {
    width: 150px;
}

.flex {
    display: flex;
    width: 100%;
}

.flex .flexItem {
    flex: 1
}

.captchaPanel {
    width: 110px;
    padding-left: 10px;
}

.captchaPanel img {
    width: 100px;
    cursor: pointer;
}

.verifycodePanel {
    width: 110px;
    padding-left: 10px;
}

.verifycodePanel .el-button {
    width: 100px;
}
</style>